//
//  YCAlertView4.m
//  DemoAlertView
//
//  Created by 唐可雄 on 16/9/27.
//  Copyright © 2016年 tangkexiong. All rights reserved.
//

#import "YCAlertView4.h"

#define kAnimationDuration 0.3f

@interface YCAlertView4 () {
    UIWindow *_window;      /// 当前对话框所在的窗口
    UIWindow *_oldWindow;   /// 之前的窗口
}

@end

@implementation YCAlertView4

#pragma mark - Override Methods

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor clearColor];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Public Methods

- (void)show {
    _window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _window.windowLevel = 440.f;
    _window.rootViewController = self;
    _oldWindow = [UIApplication sharedApplication].keyWindow;
    [_window makeKeyAndVisible];
    
    [self showAnimation];
}

- (void)dismiss {
    [self dismissAnimation];
}

#pragma mark - Private Methods

/// 对话框出现动画
- (void)showAnimation {
    [UIView animateWithDuration:kAnimationDuration animations:^{
        self.bgView.alpha = 0.5f;
    } completion:^(BOOL finished) {
        
    }];
    
    CAKeyframeAnimation *popAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    popAnimation.duration = kAnimationDuration;
    popAnimation.values = @[[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.01f, 0.01f, 1.0f)],
                            [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1f, 1.1f, 1.0f)],
                            [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9f, 0.9f, 0.9f)],
                            [NSValue valueWithCATransform3D:CATransform3DIdentity]];
    popAnimation.keyTimes = @[@0.2f, @0.5f, @0.75f, @1.0f];
    popAnimation.timingFunctions = @[[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                     [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                     [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [self.alertView.layer addAnimation:popAnimation forKey:nil];
}

/// 对话框消失动画
- (void)dismissAnimation {
    [UIView animateWithDuration:kAnimationDuration animations:^{
        self.bgView.alpha = 0.0f;
        self.alertView.alpha = 0.0f;
    } completion:^(BOOL finished) {
        [_window resignKeyWindow];
        [_oldWindow resignKeyWindow];
        
        _window = nil;
    }];
}

@end
